package com.citasgoo.aliyunFacility.util;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.citasgoo.aliyunFacility.api.AliyunKey;
import com.citasgoo.aliyunFacility.api.EmailEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class AliyunEmailUtil {

    private final static Logger logger = LoggerFactory.getLogger(AliyunEmailUtil.class);

    public static final String TO_ADDRESS = "TO_ADDRESS";
    public static final String TITLE = "TITLE";
    public static final String CONTEXT = "CONTEXT";

    public static Object sendEmail(EmailEntity email) {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunKey.getAccessKeyId(), AliyunKey.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            // request.setVersion("2017-06-22");//
            // 如果是除杭州region外的其它region（如新加坡region）,必须指定为2017-06-22
            request.setAccountName(AliyunKey.getFromAccount());
            request.setFromAlias(AliyunKey.getFromAlias());
            request.setAddressType(1);
            request.setTagName(AliyunKey.getTagName());
            request.setReplyToAddress(true);
            request.setToAddress(email.getToAddress());
            // 可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
            // request.setToAddress("邮箱1,邮箱2");
            request.setSubject(email.getTitle());
            request.setHtmlBody(email.getContext());
            SingleSendMailResponse httpResponse = client.getAcsResponse(request);
            return httpResponse;
        } catch (ClientException e) {
            e.printStackTrace();
            return e.getErrMsg();
        }
    }

    public static String sendEmail(Map<String, String> param) {
        EmailEntity email = new EmailEntity();
        if (StringUtil.isBlank(param.get(TO_ADDRESS))) {
            return "{'Code':'failed','Message':'目标邮件地址为空'}";
        }
        email.setToAddress(param.get(TO_ADDRESS));
        email.setTitle(param.get(TITLE));
        email.setContext(param.get(CONTEXT));
        Object result = sendEmail(email);
        if (result.getClass().getSimpleName().equals("SingleSendMailResponse")) {
            return "{'Code':'OK','Message':'" + JSON.toJSON(result).toString() + "'}";
        } else {
            return "{'Code':'failed','Message':'" + result + "'}";

        }
    }
}

